package com.aiti.lulian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.framework.commons.dictmodel.entity.SysDictData;
import com.aiti.framework.commons.dictmodel.mapper.SysDictDataMapper;
import com.aiti.lulian.dto.ProductAttributeDto;
import com.aiti.lulian.dto.ProductInfoDto;
import com.aiti.lulian.dto.ProductNewInfoDto;
import com.aiti.lulian.dto.SysAttachmentDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.service.IProductAttributeService;
import com.aiti.lulian.service.IProductDetailedService;
import com.aiti.lulian.service.IProductNewService;
import com.aiti.lulian.service.ISysAttachmentService;
import com.aiti.lulian.vo.ProductDetailsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * description:
 * auth fcb
 * date 2025-04-16 09:57
 **/
@Service
@Slf4j
public class ProductNewImplService extends BaseSerivceImpl<ProductNewMapper, ProductNew> implements IProductNewService {

    @Autowired
    private LuLianEnterpriseMapper luLianEnterpriseMapper;
    @Autowired
    private LuLianEnterpriseUserMapper enterpriseUserMapper;
    @Autowired
    private ProductNewMapper productMapper;
    @Autowired
    private ProductSalesMapper productSalesMapper;
    @Autowired
    private IProductAttributeService attributeService;
    @Autowired
    private ISysAttachmentService sysAttachmentService;
    @Autowired
    private IProductDetailedService productDetailedService;
    @Autowired
    private LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;

    /**
     * 新增产品。参考 ProductServiceImpl.addProduct()，
     * 去掉了远程调用的逻辑只保存本地表
     *
     * @param dto
     * @param userId
     */
    @Override
    public void addProduct(ProductNewInfoDto dto, String userId) {
        log.info("新增产品-演示用，参数：{}", JSONUtil.toJsonStr(dto));
        ProductNew product = new ProductNew();
        BeanUtil.copyProperties(dto, product, "attachments", "attributes");
        product.setBaseId(IdUtil.simpleUUID());
        //管理员
        if (StringUtils.isNotBlank(dto.getAdminRole())) {
            LuLianEnterprise enterprise = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("unicode", dto.getUscc()));
            if (enterprise == null) {
                throw new RuntimeException("没有找到" + dto.getUscc() + "的企业信息");
            }
            LuLianEnterprise enterpriseSx = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", enterprise.getBaseId()));
            if (enterpriseSx == null) {
                throw new RuntimeException("该企业没有填写企业上线资料");
            }

            product.setEnterpriseId(enterprise.getBaseId());
            product.setStatus("1");
        } else {
            product.setStatus("1");
        }

        if (NumberUtil.isNumber(dto.getBaseNote())) {
            product.setPrice(new BigDecimal(dto.getBaseNote()));
            product.setBaseNote("");
        }
        product.setCreator(userId);
        product.setBaseCreateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        product.setBaseUpdateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        productMapper.insert(product);

        //保存单位
        ProductSales sales = ProductSales.builder()
                .baseId(IdUtil.simpleUUID())
                .productId(product.getBaseId())
                .unit(dto.getUnit())
                .build();
        productSalesMapper.insert(sales);

        //保存产品属性
        List<ProductAttributeDto> attributes = dto.getAttributes();
        if (CollectionUtil.isNotEmpty(attributes)) {
            attributes.forEach(item -> {
                item.setBaseId(IdUtil.simpleUUID());
                item.setProductId(product.getBaseId());
            });

            List<ProductAttribute> list = new ArrayList<>();

            for (ProductAttributeDto item : attributes) {
                ProductAttribute temp = new ProductAttribute();
                temp.setBaseId(item.getBaseId());
                temp.setProductId(product.getBaseId());
                temp.setBaseName(item.getBaseName());
                temp.setBaseValue(item.getBaseValue());
                list.add(temp);
            }
            if (CollectionUtil.isNotEmpty(list)) {
                attributeService.saveBatch(list);
            }
        }

        //保存图片
        List<SysAttachmentDto> attachments = dto.getAttachments();
        if (CollectionUtil.isNotEmpty(attachments)) {
            int i = 0;
            for (SysAttachmentDto attachment : attachments) {
                attachment.setBaseId(IdUtil.simpleUUID());
                attachment.setRelId(product.getBaseId());
                if (i == 0) {
                    attachment.setCategory("pic");
                } else {
                    attachment.setCategory("other");
                }
                i++;
            }
            List<SysAttachment> sysAttachments = BeanUtil.copyToList(attachments, SysAttachment.class);
            sysAttachmentService.saveBatch(sysAttachments);
        }

        //保存长图
        ProductDetailed productDetailed = productDetailedService.getOne(new QueryWrapper<ProductDetailed>().eq("product_id", product.getBaseId()));
        if (productDetailed == null) {
            productDetailed = new ProductDetailed();
            productDetailed.setBaseId(IdUtil.simpleUUID());
            productDetailed.setProductId(product.getBaseId());
            productDetailed.setContent(dto.getBaseIntroduction());
        } else {
            productDetailed.setContent(dto.getBaseIntroduction());
        }
        productDetailedService.saveOrUpdate(productDetailed);
    }

    @Override
    public Page<ProductNew> queryProductList(Page<ProductNew> page, ProductNewInfoDto dto, String userId) {
        log.info("查询商品列表-演示用，参数：{}", JSONUtil.toJsonStr(dto));
        QueryWrapper<ProductNew> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(dto.getDeptId())) {
            wrapper.eq("dept_id", dto.getDeptId());
        }
        if (StringUtils.isNotBlank(dto.getBaseName())) {
            wrapper.like("base_name", dto.getBaseName());
        }
        if (StringUtils.isNotBlank(dto.getProductType()) && !"全部".equals(dto.getProductType())) {
            wrapper.eq("product_type", dto.getProductType());
        }
        if(StringUtils.isNotBlank(dto.getProvince())) {
            wrapper.eq("province", dto.getProvince());
        }
        if(StringUtils.isNotBlank(dto.getCity())) {
            wrapper.eq("city", dto.getCity());
        }
        if(StringUtils.isNotBlank(dto.getCounty())) {
            wrapper.eq("county", dto.getCounty());
        }
        if(StringUtils.isNotBlank(dto.getProvinceName())) {
            wrapper.eq("province_name", dto.getProvinceName());
        }
        if(StringUtils.isNotBlank(dto.getCityName())) {
            wrapper.eq("city_name", dto.getCityName());
        }
        if(StringUtils.isNotBlank(dto.getCountyName())) {
            wrapper.eq("county_name", dto.getCountyName());
        }
        // 先按 sort 字段从小到大排序
        // 如果 sort 相同,则按照发布时间倒序排序
        wrapper.orderByAsc("ISNULL(sort), sort")
                .orderByDesc("base_update_time");
        Page<ProductNew> productPage = productMapper.selectPage(page, wrapper);
        // 查询图片
        List<ProductNew> records = productPage.getRecords();
        records.forEach(item -> {
            List<SysAttachment> sysAttachments = sysAttachmentService.getByRelId(item.getBaseId());
            item.setAttachmentList(sysAttachments);
        });
        return productPage;
    }

    @Override
    public ProductDetailsVo queryNewProductDetail(String userId, String productId) {

        ProductDetailsVo product = this.baseMapper.queryNewProductDetail(productId);
        if(product == null){
            return new ProductDetailsVo();
        }
        // 商品单位
        ProductSales productSales = productSalesMapper.selectOne(new QueryWrapper<ProductSales>().eq("product_id", productId));
        product.setProductSales(productSales);
        // 商品图片
        List<SysAttachment> pics = sysAttachmentService.getByRelId(productId);
        product.setAttachments(pics);
        if(CollectionUtil.isNotEmpty(pics)){
            product.setPic(pics.get(0).getFullPath());
        }
        // 商品属性
        List<ProductAttribute> attributes = attributeService.list(new QueryWrapper<ProductAttribute>().eq("product_id", productId));
        product.setAttributes(attributes);

        return product;
    }

    /**
     * 在前500个商品中随机挑选4个
     * @param num
     * @return
     */
    @Override
    public List<ProductDetailsVo> queryRandomProduct(Integer num) {
        List<String> baseIdList = productMapper.queryProductBaseId();
        if (CollectionUtil.isEmpty(baseIdList)) {
            return new ArrayList<>();
        }
        if(baseIdList.size() <= 4) {
            return productMapper.queryRandomProduct(baseIdList);
        }
        if(num == null) {
            num = 4;
        }
        List<String> idList = new ArrayList<>(5);
        int i=0;
        while (i < num) {
            int random = RandomUtil.randomInt(0, baseIdList.size());
            String id = baseIdList.get(random);
            if(idList.contains(id)) {
                continue;
            }
            idList.add(id);
            i++;
        }

        List<ProductDetailsVo> productDetailsVos = productMapper.queryRandomProduct(idList);
        return productDetailsVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProductById(ProductNewInfoDto dto, String userId) {
        if(StrUtil.isEmpty(dto.getBaseId())) {
            throw new BusinessException("商品ID不能为空");
        }
        ProductNew product = new ProductNew();
        BeanUtil.copyProperties(dto,product,"attachments","attributes");
        if(NumberUtil.isNumber(dto.getBaseNote())){
            product.setPrice(new BigDecimal(dto.getBaseNote()));
            dto.setBaseNote(null);
            product.setBaseNote(null);
        }else{
            product.setPrice(null);
        }
        //修改时间为当前时间
        product.setBaseUpdateTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        productMapper.updateById(product);

        //更新图片
        //删除图片
        sysAttachmentService.remove(new QueryWrapper<SysAttachment>().eq("rel_id", product.getBaseId()));
        //重新插入图片
        //保存图片
        List<SysAttachmentDto> attachments = dto.getAttachments();
        if(CollectionUtil.isNotEmpty(attachments)){
            int i = 0;
            for(SysAttachmentDto attachment : attachments){
                attachment.setBaseId(IdUtil.simpleUUID());
                attachment.setRelId(product.getBaseId());
                if(i == 0){
                    attachment.setCategory("pic");
                }else{
                    attachment.setCategory("other");
                }
                i++;
            }
            List<SysAttachment> sysAttachments = BeanUtil.copyToList(attachments, SysAttachment.class);
            sysAttachmentService.saveBatch(sysAttachments);
        }

        //删除属性
        attributeService.remove(new QueryWrapper<ProductAttribute>().eq("product_id", product.getBaseId()));
        //重新插入属性
        //保存产品属性
        List<ProductAttributeDto> attributes = dto.getAttributes();
        if(CollectionUtil.isNotEmpty(attributes)){
            attributes.forEach(item -> {
                item.setBaseId(IdUtil.simpleUUID());
                item.setProductId(product.getBaseId());
            });
            List<ProductAttribute> list = new ArrayList<>();

            for(ProductAttributeDto item : attributes){
                ProductAttribute temp = new ProductAttribute();
                temp.setBaseId(item.getBaseId());
                temp.setProductId(product.getBaseId());
                temp.setBaseName(item.getBaseName());
                temp.setBaseValue(item.getBaseValue());
                list.add(temp);
            }
            if(!list.isEmpty()){
                attributeService.saveBatch(list);
            }
        }

        //保存长图
        ProductDetailed productDetailed = productDetailedService.getOne(new QueryWrapper<ProductDetailed>().eq("product_id", product.getBaseId()));
        if(productDetailed == null){
            productDetailed = new ProductDetailed();
            productDetailed.setBaseId(IdUtil.simpleUUID());
            productDetailed.setProductId(product.getBaseId());
            productDetailed.setContent(dto.getBaseIntroduction());
        }else{
            productDetailed.setContent(dto.getBaseIntroduction());
        }
        productDetailedService.saveOrUpdate(productDetailed);
        //保存单位
        productSalesMapper.delete(new QueryWrapper<ProductSales>().eq("product_id", product.getBaseId()));
        ProductSales sales = ProductSales.builder()
                .baseId(IdUtil.simpleUUID())
                .productId(product.getBaseId())
                .unit(dto.getUnit())
                .build();
        productSalesMapper.insert(sales);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteByProductId(String productId) {
        // 删除图片
        sysAttachmentService.remove(new QueryWrapper<SysAttachment>().eq("rel_id", productId));
        //删除属性
        attributeService.remove(new QueryWrapper<ProductAttribute>().eq("product_id", productId));
        // 删除长图
        productDetailedService.remove(new QueryWrapper<ProductDetailed>().eq("product_id", productId));
        // 删除单位
        productSalesMapper.delete(new QueryWrapper<ProductSales>().eq("product_id", productId));
        // 删除商品
        productMapper.deleteById(productId);
    }

}
